package com.reggie.module.controller;

import com.reggie.common.ResultResponseVo;
import com.reggie.module.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;

import static com.reggie.common.Constant.*;

/**
 * @Author 早睡蛋
 * @Date 2022/9/21 20:17:21
 * @Desc:
 */
@RestController
@RequestMapping("/common")
@Slf4j
@CrossOrigin
@Api(tags = "文件上传下载管理")
public class UploadController {

    @Value("${dishImages.dir}")
    private String dishImages;

    @Value("${setmealImages.dir}")
    private String setmealImages;

    @Autowired
    private DishService dishService;


    @PostMapping("/dishUpload")
    @ApiOperation("菜品图片上传")
    public ResultResponseVo dishUpload(MultipartFile file) {
        return dishService.upload(file, dishImages,DISH_IMAGES);
    }

    @PostMapping("/setmealUpload")
    @ApiOperation("套餐图片上传")
    public ResultResponseVo setmealUpload(MultipartFile file) {
        return dishService.upload(file, setmealImages,SETMEAL_IMAGES);
    }

    /**
     * 下载文件
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            //输入流，读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(URL + name));
            //输出流，写回浏览器中显示
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
